package com.lgy.springboot_example.controller;

import com.alibaba.fastjson.JSONObject;
import com.lgy.springboot_example.utils.DataResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Api(tags = "redis操作")
@RequestMapping("redis")
@RestController
public class RedisTestController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("keyTest")
    @ApiOperation("string类型key测试")
    public DataResult<Object> keyTest() {
        JSONObject data = new JSONObject();
        data.put("id", 1);
        data.put("msg", "redis操作");
        data.put("code", 666);
        redisTemplate.opsForValue().set("stringKey", data.toJSONString());
        redisTemplate.opsForValue().set("stringKey2", data.toJSONString(), 30, TimeUnit.SECONDS);//30秒之后过期
//        redisTemplate.hasKey("stringKey");      //检查key是否存在，返回boolean值
//        redisTemplate.getExpire("stringKey2");    //根据key获取过期时间
//        redisTemplate.delete("stringKey");       //根据key删除缓存
        return new DataResult<>();
    }

    @GetMapping("listKeyTest")
    @ApiOperation("list类型key测试")
    public DataResult<Object> listKeyTest() {
        redisTemplate.opsForList().rightPush("myData:listKey", "JAVA");
        redisTemplate.opsForList().rightPush("myData:listKey", "PYTHON");
        redisTemplate.opsForList().rightPush("myData:listKey", "C++");
        //获取Redis list里面所有的数据
        List<String> listData = redisTemplate.opsForList().range("myData:listKey", 0, -1);
        //获取Redis list数据的总长度
        Long size = redisTemplate.opsForList().size("myData:listKey");
        JSONObject data = new JSONObject();
        data.put("listData", listData);
        data.put("size", size);
        //删除list里所有的元素
        redisTemplate.opsForList().trim("myData:listKey", 0, 0);
        redisTemplate.opsForList().leftPop("myData:listKey");
        return new DataResult<>(data);
    }
}
